<template>
  <div calss='wrap' style='height: 100%; background:#f0f2f5; padding: 20px;'>
    <div class="formCreater" style='height: 100%; overflow: auto;'>
      <div class="addForm">
        <el-form :label-width="'100px'" style='padding:20px; border: 1px solid #ddd;' ref="addForm" :model="addForm" :inline=true>
          <el-form-item label="表单分类">
              <el-select v-model="addForm.type" placeholder="请选择" style = 'width: 217px;'>
                <el-option label="随访表单" value='1'></el-option>
                <el-option label="随访表单2" value='2'></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="表单功能">
              <el-select v-model="addForm.functionType" placeholder="请选择" style = 'width: 217px;'>
                <el-option label="普通表单" value='1'></el-option>
                <el-option label="分值表单" value='2'></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="表单名称">
            <el-input v-model="addForm.name" style='width: 217px;'></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div style='display: flex;'>
        <div style="flex: 1;  background:#fff; margin: 20px 20px 0 0">
          <el-form :label-width="'100px'" class="b-a" :label-position="'top'" :disabled=true>
            <draggable :clone="cloneData" :list="form_list" :options="dragOptions1" >
              <transition-group class="form-list-group" type="transition" :name="'flip-list'" tag="div">
                <renders v-for="(element,index) in form_list" :key="index" :ele="element.ele" :obj="element.obj || {}"></renders>
              </transition-group>
            </draggable>
          </el-form>
        </div>
        <div style="flex: 1;  background:#fff; margin-top: 20px">
          <el-form ref="formValidate" class="b-a" :label-width="'100px'" :model="formData" @submit.native.prevent :label-position="'top'" :disabled=true style='padding-bottom: 76px;'>
            <el-alert title="警告提示的文案" type="warning" description="未绑定数据字典控件无效" show-icon>
            </el-alert>
            <draggable :list="sortable_item" :options="dragOptions2">
              <transition-group class="form-list-group" type="transition" :name="'flip-list'" tag="div">
                <renders @handleRemoveEle="removeEle" @handleConfEle="confEle" @changeVisibility="changeVisibility" v-for="(element,index) in sortable_item" :key="index" :index="index" :ele="element.ele" :obj="element.obj || {}" :data="formData" @handleChangeVal="val => handleChangeVal(val,element)" :sortableItem="sortable_item" :config-icon="true">
                </renders>
              </transition-group>
            </draggable>
          </el-form>
          <div style='margin: -56px 0 0 20px;'>
            <el-button type="primary" @click="handleSubmit()">生成表单</el-button>
            <el-button type="ghost" @click="handleReset()" style="margin-left: 8px">清空表单</el-button>
          </div>
        </div>
      </div>
      <el-dialog :visible.sync="showModal" :title="'配置' + modalFormData.modalTitle + '属性'" :mask-closable="false">
        <el-form class="form_content" :label-width="'100px'" :model="modalFormData" ref="modalFormData">
          <el-form-item label="控件名称：" v-if="typeof modalFormData.label != 'undefined'" >
            <el-input v-model="modalFormData.label" placeholder="请输入控件名称" :maxlength="20" style = 'width: 200px;'></el-input>
          </el-form-item>
          <!-- <el-form-item label="数据字典：" v-if="showModal">
            <el-select v-model="modalFormData.dict" filterable @change="handleDataDictChange">
              value绑定json字符串的原因是，需要用到parent_name，当handleDataDictChange触发，赋值到modalFormData 
              <el-option :disabled="dataDictSelected.indexOf(item.id) >= 0" v-for="item in dataDictList" :value="JSON.stringify({
                id: item.id, parent_name: item.parent_name, label: item.label})" :key="item.id">{{ item.label }}</el-option>
            </el-select>
          </el-form-item>-->
          <el-form-item label="name属性：" v-if="typeof modalFormData.name != 'undefined'" >
            <el-input v-model="modalFormData.name" placeholder="" style = 'width: 200px;'></el-input>
          </el-form-item>

          <el-form-item v-if='modalFormData.type === "radio" || modalFormData.type === "checkbox" || modalFormData.items' v-for="(domain, index) in modalFormData.items" :label="'选项' + index" :key="domain.label_value" >
            <el-input v-model="domain.label_name" style = 'width: 200px;'></el-input>
            <el-button @click.prevent="removeDomain(domain)">删除</el-button>
          </el-form-item>
          <el-form-item v-if='modalFormData.type === "radio" || modalFormData.type === "checkbox"'>
            <el-button @click="addDomain">新增选项</el-button>
          </el-form-item>

          <el-form-item label="关联数据：" v-if="typeof modalFormData.relation != 'undefined'">
            <!-- 当绑定name并且当前relationList存在数据时候才可以关联字段 -->
            <el-checkbox :disabled="!modalFormData.name || !relationList.length" v-model="modalFormData.relation">是否关联字段</el-checkbox>
          </el-form-item>
          <el-form-item label="关联配置：" v-if="typeof modalFormData.relation != 'undefined' && modalFormData.relation">
            <el-select v-model="modalFormData.relation_name" class="inline-block" style="width: 150px" @on-change="_=>modalFormData.relation_value = ''">
              <el-option :disabled="item.obj.name == modalFormData.name" v-for="(item,index) in relationList" :key="index" :value="item.obj.name">{{item.obj.label}}</el-option>
            </el-select>
            <p class="inline-block padder-sm">等于</p>
            <el-select v-model="modalFormData.relation_value" class="inline-block" style="width: 150px">
              <el-option v-for="(item,index) in relationValue" :key="index" :value="item.label_value">{{item.label_name}}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="placeholder：" v-if="typeof modalFormData.placeholder != 'undefined'">
            <el-input v-model="modalFormData.placeholder" placeholder="请输入placeholder" style = 'width: 200px;'></el-input>
          </el-form-item>
          <el-form-item label="最大长度：" v-if="typeof modalFormData.maxLength != 'undefined'">
            <el-input-number v-model="modalFormData.maxLength" placeholder="请输入文本限制最大长度">
            </el-input-number>
          </el-form-item>
          <el-form-item label="最大限制：" v-if="typeof modalFormData.maxSize != 'undefined'">
            <el-input-number :formatter="value => `${value}kb`" :parser="value => value.replace('kb', '')" v-model="modalFormData.maxSize" placeholder="请输入上传文件最大限制">
            </el-input-number>
          </el-form-item>
          <el-form-item label="上边距：" v-if="typeof modalFormData.marginTop != 'undefined'">
            <el-input-number :formatter="value => `${value}px`" :parser="value => value.replace('px', '')" v-model="modalFormData.marginTop" placeholder="请输入标签上边距">
            </el-input-number>
          </el-form-item>
          <el-form-item label="下边距：" v-if="typeof modalFormData.marginBottom != 'undefined'">
            <el-input-number :formatter="value => `${value}px`" :parser="value => value.replace('px', '')" v-model="modalFormData.marginBottom" placeholder="请输入标签下边距">
            </el-input-number>
          </el-form-item>
          <el-form-item label="详细地址：" v-if="typeof modalFormData.details_address != 'undefined'">
            <el-checkbox v-model="modalFormData.details_address">是否需要详细地址</el-checkbox>
          </el-form-item>
          <el-form-item label="是否必填：" v-if="typeof modalFormData.require != 'undefined'">
            <el-checkbox v-model="modalFormData.require">必填</el-checkbox>
          </el-form-item>
          <el-form-item label="校验错误：" v-if="typeof modalFormData.ruleError != 'undefined'">
            <el-input v-model="modalFormData.ruleError" placeholder="请输入校验错误提示" style = 'width: 200px;'></el-input>
          </el-form-item>
          <el-form-item label="是否多选：" v-if="typeof modalFormData.multiple != 'undefined' && modalFormData.type != 'address'">
            <el-checkbox v-model="modalFormData.multiple">多选</el-checkbox>
          </el-form-item>
          <el-form-item label="时间格式：" v-if="typeof modalFormData.format != 'undefined'">
            <el-radio-group v-model="modalFormData.format">
              <el-radio label="yyyy年MM月dd日"></el-radio>
              <el-radio label="yyyy-MM-dd HH:mm"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="行内元素：" v-if="typeof modalFormData.inlineBlock != 'undefined'">
            <el-checkbox v-model="modalFormData.inlineBlock">是</el-checkbox>
          </el-form-item>
          <el-form-item label="显示行数：" v-if="typeof modalFormData.maxRows != 'undefined'">
            <el-slider v-model="modalFormData.maxRows" :min="2" :max="10"></el-slider>
          </el-form-item>
          <el-form-item label="标题大小：" v-if="typeof modalFormData.level != 'undefined'">
            <el-input-number :max="6" :min="1" v-model="modalFormData.level"></el-input-number>
          </el-form-item>
          <el-form-item label="字体颜色：" v-if="typeof modalFormData.color != 'undefined'">
            <el-color-picker v-model="modalFormData.color" />
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button type="text" @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="modalFormData.loading" @click="handleOk">确定</el-button>
        </div>
      </el-dialog>
      <!-- 预览 -->
      <el-dialog :visible.sync="renderShow">
        <div>
          <render :template_form='template_form' @closeRenderShow="closeRenderShow"></render>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import draggable from 'vuedraggable'
import render from '@/formCreater/components/render'
import form_list from '@/formCreater/components/custom_form/FormList'
import { getAllItem } from '@/api/formCreater/formCreater'
import { readForm, postForm } from '@/api/knowledgeManage/followupForm'
export default {
  components: { draggable, render },
  mounted() {
    const id = this.$route.params.id
    console.log('表单id:' + id)
    if (id > 0) {
      readForm(id).then(res => {
        this.addForm = res.data.info
        this.sortable_item = JSON.parse(res.data.info.content || '[]')
      })
    }
  },
  data() {
    return {
      addForm: {},
      form_list: form_list,
      sortable_item: [],
      showModal: false,
      // 深拷贝对象，防止默认空对象被更改
      // 颜色选择器bug，对象下color不更新
      modalFormData: {
        color: '',
        loading: false
      },
      formData: {},
      dataDict: [],
      saveDictValue: {},
      // preview
      renderShow: false,
      template_form: [],
      domains: []
    }
  },
  methods: {
    // 单选或多选  添加 删除 选项
    removeDomain(item) {
      var index = this.modalFormData.items.indexOf(item)
      if (index !== -1) {
        this.modalFormData.items.splice(index, 1)
      }
    },
    addDomain() {
      this.modalFormData.items.push({
        label_name: '',
        label_value: Date.now()
      })
    },
    closeRenderShow() {
      this.renderShow = false
    },
    // 克隆表单提交事件
    handleSubmit() {
      // 表单内容的 schema .  可以通过formSchema 的数据动态生成表单，这个是要保存到后台的
      var formSchema = JSON.stringify(this.sortable_item.filter(v => {
        return !!v.obj.name
      }))
      console.log('表单生成.....')
      console.log(formSchema)
      const query = Object.assign({}, this.addForm, { content: formSchema })
      postForm(query).then(res => {
        console.log(res)
      })
      localStorage.setItem('template_form', formSchema)
      this.$message({
        message: '生成表单成功！',
        type: 'success'
      })
      this.$root.closeTag()
    },
    // 清空克隆表单
    handleReset() {
      this.sortable_item = []
    },
    // modal内数据字典选项发生改变触发事件
    handleDataDictChange(val) {
      // 选中后，val默认赋值到modalFormData.dict
      // const obj = JSON.parse(val)
      // this.saveDictValue = obj
      // 数据加载中，禁止modal_submit提交按钮
      this.$set(this.modalFormData, 'loading', true)
      // getItemById(obj.id).then(d => {
      // console.log(d)
      this.modalFormData = Object.assign({}, this.modalFormData, {
        // name: d.data.name,
        loading: false,
        // items: this.domains,
        // items: d.data.items,
        parent_name: this.domains.parent_name
      })
      // this.modalFormData.dict = obj.label
      // this.modalFormData.label = obj.label
      // })
      // this.$http.get(`/static/label.${obj.id}.json`).then(d => {
      //   this.modalFormData = Object.assign({}, this.modalFormData, {
      //     name: d.data.name,
      //     loading: false,
      //     items: d.data.items,
      //     parent_name: obj.parent_name
      //   })
      // })
    },
    // 控件回填数据
    handleChangeVal(val, element) {
      this.$set(this.formData, element.obj.name, val)
    },
    // https://github.com/SortableJS/Vue.Draggable#clone
    // 克隆,深拷贝对象
    cloneData(original) {
      // 添加一个modal标题
      original.obj.modalTitle = original.obj.label || ''
      // 深拷贝对象，防止默认空对象被更改
      return JSON.parse(JSON.stringify(original))
    },
    // modal点击确定执行事件
    handleOk() {
      this.handleDataDictChange()
      const index = this.modalFormData.listIndex
      this.modalFormData.dict = JSON.stringify(this.saveDictValue)
      this.sortable_item[index].obj = Object.assign({},
        this.sortable_item[index].obj,
        this.modalFormData
      )
      this.handleCancel()
    },
    // modal点击取消执行事件，清空当前modal内容
    handleCancel() {
      this.showModal = false
      setTimeout(_ => {
        this.modalFormData = {
          color: '',
          loading: false
        }
      }, 500)
    },
    // 显示modal,配置被克隆控件
    confEle(index) {
      const list_temp = Object.assign({}, this.sortable_item[index])
      for (const i in list_temp.obj) {
        this.modalFormData[i] = list_temp.obj[i]
      }
      // 配置项中未找到color，删除modalFormData中自带color属性
      if (!list_temp.obj['color']) delete this.modalFormData.color
      // 设置被配置控件的index，便于完成配置找到相应对象赋值
      this.modalFormData.listIndex = index
      // Vue 不能检测到对象属性的添加或删除
      this.modalFormData = Object.assign({}, this.modalFormData)
      this.showModal = true
    },
    // 删除克隆控件
    removeEle(index) {
      const name = this.sortable_item[index].obj.name
      this.sortable_item.splice(index, 1)
      if (!name) return
      for (const i in this.sortable_item) {
        // 当relation为true并且关联字段被确认
        if (this.sortable_item[i].obj.relation && this.sortable_item[i].obj.relation_name === name) {
          this.$set(this.sortable_item[i].obj, 'relation', false)
          this.$set(this.sortable_item[i].obj, 'relation_name', '')
          this.$set(this.sortable_item[i].obj, 'relation_value', '')
          break
        }
      }
    },
    // 更改当前渲染字段是否显示
    changeVisibility(index, visibility) {
      this.$set(this.sortable_item[index].obj, 'visibility', visibility)
    }
  },
  watch: {
    showModal(val) {
      if (!val) {
        this.handleCancel()
      }
    }
  },
  computed: {
    // 数据字典已选择项
    dataDictSelected() {
      return this.sortable_item.map(v => {
        const obj = JSON.parse(v.obj.dict || '{}')
        return obj.id || -1
      })
    },
    // 对应控件的数据字典
    dataDictList() {
      return this.dataDict.filter(v => {
        return v.type === this.modalFormData.type
      })
    },
    // 拖拽表单1
    dragOptions1() {
      return {
        animation: 0,
        ghostClass: 'ghost',
        // 分组
        group: {
          name: 'shared',
          pull: 'clone',
          revertClone: false
        },
        // 禁止拖动排序
        sort: false
      }
    },
    // 拖拽表单2
    dragOptions2() {
      return {
        animation: 0,
        ghostClass: 'ghost',
        group: {
          // 只允许放置shared的控件,禁止pull
          put: ['shared']
        }
      }
    },
    // 被关联字段列表
    relationList() {
      // 只有type内三项可作为被关联字段
      const type = ['select', 'radio', 'checkbox']
      const arr = this.sortable_item.filter(k => {
        return type.indexOf(k.ele) >= 0 && !!k.obj.name
      })
      return arr
    },
    // 被关联字段数据
    relationValue() {
      const name = this.modalFormData.relation_name
      let items = []
      if (!name) return items
      for (const i in this.sortable_item) {
        if (this.sortable_item[i].obj.name === name) {
          items = this.sortable_item[i].obj.items
        }
      }
      return items
    }
  },
  created() {
    getAllItem().then(d => {
      this.dataDict = d.data.items
    })
  }
}
</script>
<style lang = 'scss'>
.addForm {
  background: #fff;
}
.inline {
  display: inline-block;
}

.m-l-lg {
  margin-left: 30px;
}

.wrapper {
  padding: 15px;
}

.inline-block {
  display: inline-block;
}

.padder-sm {
  padding-right: 10px;
  padding-left: 10px;
}

.b-a {
  border: 1px solid #ccc;
  background: #fff;
  padding: 20px;
}

.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

.form-list-group {
  min-height: 200px;
  padding: 20px !important;
}

/* 设置items下所有鼠标样式为 move */

.items,
.items * {
  cursor: move;
}

/* 配置按钮默认位置 */

/* 例如P Hr Title按钮 */

.items .item-icon {
  transition: all 2s ease;
  position: absolute;
  top: -18px;
  right: 0px;
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}

/* form控件下配置按钮位置 */

.ivu-form-item.items .item-icon {
  top: -25px;
}

/* 配置按钮样式 */

.item-icon i {
  cursor: pointer !important;
  margin-right: 5px;
}

.items:hover .item-icon {
  transition: inherit;
  opacity: 1;
  max-height: 50px;
}

/* 提交按钮下方无 margin-bottom */

.form_content .ivu-form-item:last-child {
  margin-bottom: 0;
}

/* 表单校验选项样式 */

.ivu-form-item-required .ivu-form-item-label:before {
  content: "";
}

.items.sortable-items-required .ivu-form-item-label:before {
  content: "*";
  display: inline-block;
  margin-right: 4px;
  line-height: 1;
  font-family: SimSun;
  font-size: 12px;
  color: #ed3f14;
}
.el-radio-group{
  display: flex;
  flex-wrap: wrap;
  label{
    margin:5px 30px 5px 0 !important;
  }
}
</style>
